package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.RuleDetailMapper;
import com.indusfo.spc.mapper.RuleMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.RuleDetailService;
import com.indusfo.spc.untlis.StringUtils;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author chenm
 * @create 2019-07-23 14:21
 */
@Service("RuleDetailService")
public class RuleDetailServiceImpl implements RuleDetailService {

    private static final Logger logger = LoggerFactory.getLogger(RuleDetailServiceImpl.class);

    @Resource
    private RuleDetailMapper ruleDetailMapper;

    @Resource
    private RuleMapper ruleMapper;
    @Resource
    private UploadMapper uploadMapper;


    /**
     * 查询
     *
     * @param ruleDetail
     */
    @Override
    public JSONObject queryRuleDetail(RuleDetail ruleDetail) {
        try {
            //获取页面的数据个数
            Integer pagesize = ruleDetail.getPagesize();
            //获取查询的页数
            Integer pageindex = ruleDetail.getPageindex();
            if(pagesize!=null && pageindex !=null){
                ruleDetail.setIncept(pagesize*(pageindex-1));
            }
            List<RuleDetail> ruleDetailList=new ArrayList();
            if(ruleDetail.getRuleId()==null){
                return  JSONObject.oK(HintMessage.QUERY_DEFEATED,   ruleDetailList,0);
            }

            //执行查询操作
            ruleDetailList=ruleDetailMapper.queryRuleDetail(ruleDetail);

            //如果页数和页面数量都不为空的情况下进行计数
            if(ruleDetailList.isEmpty()){
                return  JSONObject.oK(HintMessage.QUERY_DEFEATED,ruleDetailList,0);
            }else{
                Integer count= ruleDetailMapper.countRuleDetail(ruleDetail);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS,ruleDetailList,count);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }


    /**
     * 新增
     *
     * @param
     * @return
     */
    @Override
    public JSONObject insertRuleDetail(RuleDetail ruleDetail) {
        try {
            if (ruleDetail.getRuleDetailId() != null) {
                throw new ModifyFailedException(HintMessage.INSERT_ID);
            }
            //初始化基础数据
            if (ruleDetail.getDataState() == null) {
                ruleDetail.setDataState(1);
            }
            //判重
            checkParam(ruleDetail);
            ruleDetail.setSerialNum(1+ruleDetailMapper.countRuleDetailByRuleId(ruleDetail.getRuleId()));


            //执行新增操作
            Integer row = ruleDetailMapper.insertRuleDetail(ruleDetail);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.INSERT_DEFEATED);
            }
            return JSONObject.oK(HintMessage.INSERT_SUCCESS);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());

        }
    }
    /**
     * @Author 熊冰  //修改
     * @Date 2020/1/17 8:48
     */
    @Override
    public JSONObject updateRuleDetail(RuleDetail ruleDetail) {
        try {
            if(ruleDetail.getRuleDetailId()==null) {
                throw new ParamsErrorException(HintMessage.UPDATE_ID);
            }
            //初始化基础数据
            if(ruleDetail.getDataState()==null){
                ruleDetail.setDataState(1);
            }
            //判重
            checkParam(ruleDetail);
            //执行修改操作
            int row = ruleDetailMapper.updateRuleDetail(ruleDetail);
            if(row == 0) {
                throw new ModifyFailedException(HintMessage.UPDATE_DEFEATED);
            }
            return JSONObject.oK(HintMessage.UPDATE_SUCCESS);
        }catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }



    /**
     * 删除
     *
     * @param
     * @param dataState
     * @return
     */
    @Override
    public JSONObject deleteRuleDetail(Integer[] ruleDetailIds, Integer dataState) {
        try{
            //空值判断
            if(dataState == null) {
                throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
            }
            if(ruleDetailIds == null) {
                throw new ParamsErrorException(HintMessage.LIST_NULL);
            }
            //记录异常信息
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = HintMessage.START_VALUE;break;
                case 2:
                    msg = HintMessage.DELETE_VALUE;break;
                case 3:
                    msg = HintMessage.STOP_VALUE;break;
                default:
                    throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
            }
            //执行删除操作
            int row = ruleDetailMapper.deleteRuleDetail(ruleDetailIds,dataState);
            //声明msg字符串，用来存抛出的异常
            if (row == 0) {
                msg=msg+ HintMessage.DEFEATED_VALUE;
            } else {
                msg=msg+ HintMessage.SUCCESS_VALUE;
            }
            return JSONObject.oK(msg);
        }catch(GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }






    /**
     * 验证信息
     * @param
     */
    public void checkParam(RuleDetail ruleDetail){
        if(ruleDetail.getRuleId()==null){
            throw new ParamsErrorException(HintMessage.RULEID_NULL);
        }

//        if(ruleDetail.getRemark().getBytes().length > 100) {
//			throw new ParamsErrorException(HintMessage.REMARIK_LONG);
//		}
        if(ruleDetail.getRuleTypeId()==null){
            throw new ParamsErrorException(HintMessage.RULETYPEID_NULL);
        }
        switch (ruleDetail.getRuleTypeId()) {
            case 1:
                if(ruleDetail.getNumValue()==null){
                    throw new ParamsErrorException(HintMessage.NUMVALUE_NULL);
                }
                if(ruleDetail.getNumLength()==null){
                    throw new ParamsErrorException(HintMessage.NUMLENGTH_NULL);
                }
                if(ruleDetail.getNumStep()==null){
                    throw new ParamsErrorException(HintMessage.NUMSTEP_NULL);
                }
                break;
            case 2:
                if(ruleDetail.getRuleFormatId()==null){
                    throw new ParamsErrorException(HintMessage.RULEFORMATID_NULL);
                }
                break;
            case 3:
                if(StringUtils.isEmpty(ruleDetail.getCharValue())){
                    throw new ParamsErrorException(HintMessage.CHARVALUE_NULL);
                }
                break;
            case 4:
                if(ruleDetail.getVariateTypeId()==null){
                    throw new ParamsErrorException(HintMessage.VARIATETYPEID_NULL);
                }
                if(ruleDetail.getVariateFormatId()==null){
                    throw new ParamsErrorException(HintMessage.VARIATEFORMATID_NULL);
                }
                break;
            default:
                throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);

        }

//        Integer Counts = ruleDetailMapper.countRuleDetail(ruleDetail);
//        if (Counts !=0) {
//            throw new ParamsErrorException(HintMessage.REPEATING_DATA);
//        }
//        String remark = RuleDetail.getRemark();
//        if(remark==null){
//            remark="";
//        }
//        if(remark.length() > 100){
//            throw new ParamsErrorException("备注字数超过规定,长度100");
//        }
        /*if(RuleDetail.getRuleId() == null){
            throw new ParamsErrorException("请先选择条码规则");
        }*/
//        if(RuleDetail.getConstant() == null){
//            throw new ParamsErrorException("请选择是否是常量");
//        }
//        if(RuleDetail.getForm() == null){
//            throw new ParamsErrorException("请填写格式");
//        }
//        if (RuleDetail.getForm().length() > 50) {
//            throw new ParamsErrorException("格式字数超过规定,长度50");
//        }
//        if(RuleDetail.getType() == null){
//            throw new ParamsErrorException("请填写类型");
//        }
//        if (RuleDetail.getType().length() > 50) {
//            throw new ParamsErrorException("类型字数超过规定,长度50");
//        }
        /*if(RuleDetail.getAutoid() == null){
            throw new ParamsErrorException("请填写序号名");
        }
        if (RuleDetail.getAutoid().length() > 50) {
            throw new ParamsErrorException("序号名字数超过规定,长度50");
        }
        if(RuleDetailMapper.getRuleDetailAutoid(RuleDetail.getRuleDetailId(),RuleDetail.getAutoid()) != null){
            throw new ParamsErrorException("序号名称已存在");
        }*/

    }



    @Override
    public String checkNoRepeatExcel(RuleDetail ruleDetail){
        //条码规则类别名称
        String ruleName = ruleDetail.getRuleName();
        //类型名称
        String ruleTypeName=ruleDetail.getRuleTypeName();
        //日期格式名称
        String ruleFormatName = ruleDetail.getRuleFormatName();
        //数值初始值
        Integer numValue=ruleDetail.getNumValue();
        //常量初始值
        String charValue=ruleDetail.getCharValue();
        //数值长度
        Integer numLength = ruleDetail.getNumLength();
        //数值步长
        Integer numStep=ruleDetail.getNumStep();
        //变量参数名称
        String variateFormatName=ruleDetail.getVariateFormatName();
        //变量格式名称
        String variateTypeName=ruleDetail.getVariateTypeName();
        //变量起始值
        Integer startNum=ruleDetail.getStartNum();
        //变量结束值
        Integer endNum=ruleDetail.getEndNum();
        if(StringUtils.isBlank(ruleName) && StringUtils.isBlank(ruleTypeName) && StringUtils.isBlank(ruleFormatName) && StringUtils.isBlank(charValue) && StringUtils.isBlank(variateFormatName) &&
                StringUtils.isBlank(variateTypeName) && numValue==null && numLength==null && numStep==null && startNum==null && endNum==null){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if(ruleName==null){
            return "条码规则类别名称为空";
        }
        Map<String, Rule> ruleMap = uploadMapper.queryRule();
        if(!ruleMap.containsKey(ruleName)){
            return "条码规则类别名称输入错误/不规范";
        }
        Rule rule = ruleMap.get(ruleName);
        ruleDetail.setRuleId(rule.getRuleId());
        Map<String, Datadict> ruleTypeMap = uploadMapper.queryType(101037);
        if(!ruleTypeMap.containsKey(ruleTypeName)){
            return "条码规则类型名称输入错误/不规范";

        }
        ruleDetail.setRuleTypeId(ruleTypeMap.get(ruleTypeName).getItemId());
        if(new Integer(1).equals(ruleDetail.getRuleTypeId())){
            //数值    初始值,数值长度,数值步长,并且这三项为必填项
            if(numValue==null || "".equals(numValue)){
                return "数值初始值为空/填写不规范";
            }
            if(numValue.toString().getBytes().length>10){
                return "数值初始值长度不能超过十位数";
            }
            if(numLength==null || "".equals(numLength)){
                return "数值长度为空";
            }
            if(numLength.toString().getBytes().length>10){
                return "数值长度不能超过十位数";
            }
            if(numStep==null || "".equals(numStep)){
                return "数值步长为空";
            }
            if(numStep.toString().getBytes().length>10){
                return "数值步长不能超过十位数";
            }

        }else if(new Integer(2).equals(ruleDetail.getRuleTypeId())){
            //日期
            Map<String, Datadict> dateTypeMap = uploadMapper.queryType(101038);
            if(!dateTypeMap.containsKey(ruleFormatName)){
                return "日期格式填写错误/不规范";

            }
            ruleDetail.setRuleFormatId(dateTypeMap.get(ruleFormatName).getItemId());
        }else if(new Integer(3).equals(ruleDetail.getRuleTypeId())){
            //常量 需要填写初始值,并且初始值为必填项
            if(StringUtils.isEmpty(charValue)){
                return "常量初始值为空/填写不规范";
            }
            try {
                Double.valueOf(charValue);
                if(charValue.getBytes().length>10){
                    return "常量初始值长度不能超过10";
                }
            }catch (Exception e){
                return "常量初始值必须为数字";
            }


        }else if(new Integer(4).equals(ruleDetail.getRuleTypeId())){
            //变量 变量参数、变量格式、变量起始值、变量结束值,并且变量参数和变量格式为必填项,所填写变量起始值变量结束值必须为数字
            Map<String, Datadict> variateFormatNameMap = uploadMapper.queryType(101051);
            if(!variateFormatNameMap.containsKey(variateFormatName)){
                return "变量参数填写错误/不规范";

            }
            ruleDetail.setVariateFormatId(variateFormatNameMap.get(variateFormatName).getItemId());
            Map<String, Datadict> variateTypeNameMap = uploadMapper.queryType(101052);
            if(!variateTypeNameMap.containsKey(variateTypeName)){
                return "变量格式填写错误/不规范";

            }
            ruleDetail.setVariateTypeId(variateTypeNameMap.get(variateTypeName).getItemId());

        }
        return null;
    }

    @Override
    public JSONObject updateListRuleDetail(List<RuleDetail> ruleDetailList){
        int flag = uploadMapper.updateListRuleDetail(ruleDetailList);
        if(flag>0){
            return JSONObject.oK("新增成功");
        }
        return JSONObject.oK("新增失败");
    }

    @Override
    public JSONObject sortRuleDetail(Integer[] ruleDetailiIds) {
        try {
            if(ruleDetailiIds==null){
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            for (int i = 0; i < ruleDetailiIds.length ; i++) {

                System.out.println(ruleDetailiIds[i]);
                RuleDetail ruleDetail=new RuleDetail();
                ruleDetail.setRuleDetailId(ruleDetailiIds[i]);
                ruleDetail.setSerialNum(i+1);
                ruleDetail.setDataState(1);
                int row = ruleDetailMapper.updateRuleDetailSort(ruleDetail);
                if(row == 0) {
                    throw new ModifyFailedException(HintMessage.UPDATE_DEFEATED);
                }
            }
            return JSONObject.oK(HintMessage.UPDATE_SUCCESS);

        }catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }


    }
}
